#include "include/keyWordSearchDlg.h"
#include <QSqlDatabase>
#include <QSqlQuery>
#include <QString>
#include <QWSServer>
#include <QWSInputMethod>
#include "include/syszuxim.h"
#include "include/syszuxpinyin.h"

KeyWordSearchDlg::KeyWordSearchDlg(QWidget *parent)
    : Search(parent)
{
    //setWindowFlags(Qt::FramelessWindowHint);
    setWindowTitle(QString::fromUtf8("关键字查找"));
    setFixedSize(800, 480);

    myTimerId = 0;
    pageSeq = 1;
    numOfTotalItem = 0;
    searchStr = "";

    CreateWidget();
    CreateLayout();

    im = new SyszuxIM;
    QWSServer::setCurrentInputMethod(im);
//    im->updateHandler(QWSInputMethod::FocusIn);

}

void KeyWordSearchDlg::CreateWidget()
{
    searchBtn = new QPushButton(QString::fromUtf8("搜索"), this);
    searchLineEdit = new QLineEdit(this);
    groupBox = new QGroupBox(this);
    pageUp = new QPushButton(QString::fromUtf8("上一页"), this);
    pageDown = new QPushButton(QString::fromUtf8("下一页"), this);
    quit = new QPushButton(QString::fromUtf8("退出"), this);

    connect(searchBtn, SIGNAL(clicked()), this, SLOT(SearchItems()));
    connect(pageUp, SIGNAL(clicked()), this, SLOT(PageSeqDes()));
    connect(pageDown, SIGNAL(clicked()), this, SLOT(PageSeqInc()));
    connect(quit, SIGNAL(clicked()), this, SLOT(close()));
}

void KeyWordSearchDlg::CreateLayout()
{
    topLayout = new QHBoxLayout;
    topLayout->addStretch();
    topLayout->addWidget(searchLineEdit);
    topLayout->addWidget(searchBtn);
    topLayout->addStretch();
    topLayout->addWidget(pageUp);
    topLayout->addWidget(pageDown);
    topLayout->addWidget(quit);

    mainLayout = new QVBoxLayout;
    mainLayout->addLayout(topLayout);
    mainLayout->addWidget(groupBox);


    setLayout(mainLayout);


}

void KeyWordSearchDlg::SearchItems()
{
    QString query = BuildQuery();
    qDebug() << "查询语句: "<< query;
    numOfTotalItem = GetNumOfTotalItem(query);
    qDebug() << "总的个数："<< numOfTotalItem;
    maxPageSeq = GetMaxPages();
    qDebug() <<"最大页数："<< maxPageSeq;
    if(numOfTotalItem != 0)
    {
        UpdateSearchResult(query);
    }

}

QString KeyWordSearchDlg::obtainStr()
{
    return searchLineEdit->text();
}

QStringList KeyWordSearchDlg::obtainAreaList(QString areaStr)
{
    QRegExp rx("[A-Z][\u4e00-\u9fa5]?");
    int pos = rx.indexIn(areaStr);
    QStringList areaList = rx.capturedTexts();
    return areaList;
}

QStringList KeyWordSearchDlg::obtainRidgepoleList(QString ridgepoleStr)
{
    QRegExp rx("[0-9][0-9][\u6800-\u6810]");
    int pos = rx.indexIn(ridgepoleStr);
    QStringList ridgepoleList = rx.capturedTexts();
    return ridgepoleList;
}

QStringList KeyWordSearchDlg::obtainLayerList(QString layerStr)
{
    QRegExp rx("[0-9][0-9][\u5c40-\u5c50]");
    int pos = rx.indexIn(layerStr);
    QStringList layerList = rx.capturedTexts();
    return layerList;
}

QStringList KeyWordSearchDlg::obtainRoomList(QString roomStr)
{
    QRegExp rx("[0-9][0-9][0-9][\u6230-\u6240]?");
    int pos = rx.indexIn(roomStr);
    QStringList roomList = rx.capturedTexts();
    return roomList;
}

QStringList KeyWordSearchDlg::obtainDevNameList(QString devNameStr)
{
    QRegExp rx("[\u4e00-\u9fa5][\u4e00-\u9fa5][\u4e00-\u9fa5]*");
    int pos = rx.indexIn(devNameStr);
    QStringList devNameList = rx.capturedTexts();
    return devNameList;
}

QString KeyWordSearchDlg::BuildQuery()
{
    bool areaIsEmtpy = false;
    bool ridgepoleIsEmtpy = false;
    bool layerIsEmtpy = false;
    bool roomIsEmtpy = false;

    QStringList strArealist = obtainAreaList(obtainStr());
    QStringList strRidgepolelist = obtainRidgepoleList(obtainStr());
    QStringList strLayerlist = obtainLayerList(obtainStr());
    QStringList strRoomlist = obtainRoomList(obtainStr());
    QStringList strDevNamelist = obtainDevNameList(obtainStr());

    QString selectQuery = "";

    if(strArealist.at(0) != "")
    {
        selectQuery += QString("area = '%1' ").arg(strArealist.at(0));   //地区选项没有空
    }
    else
    {
        areaIsEmtpy = true;
    }
    if(strRidgepolelist.at(0) != "")
    {
        if(!areaIsEmtpy)
        {
            selectQuery += QString("and ridgepole = '%1' ").arg(strRidgepolelist.at(0));
        }
        else
        {
            selectQuery += QString("ridgepole = '%1' ").arg(strRidgepolelist.at(0));
        }

        ridgepoleIsEmtpy = false;

    }
    else
    {
        ridgepoleIsEmtpy = true;
    }
    if(strLayerlist.at(0) != "")
    {
        if(ridgepoleIsEmtpy && areaIsEmtpy)
        {
            selectQuery += QString("layer = '%1' ").arg(strLayerlist.at(0));
        }
        else
        {
            selectQuery += QString("and layer = '%1' ").arg(strLayerlist.at(0));
        }

        layerIsEmtpy = false;
    }
    else
    {
        layerIsEmtpy = true;
    }
    if(strRoomlist.at(0) != "")
    {
        if(areaIsEmtpy && ridgepoleIsEmtpy && layerIsEmtpy)
        {
            selectQuery += QString("room = '%1' ").arg(strRoomlist.at(0));
        }
        else
        {
            selectQuery += QString("and room = '%1' ").arg(strRoomlist.at(0));
        }

    }
    else
    {
        roomIsEmtpy = true;
    }
    if(strDevNamelist.at(0) != "")
    {
        if(areaIsEmtpy && ridgepoleIsEmtpy && layerIsEmtpy && roomIsEmtpy)
        {
            selectQuery += QString("devName = '%1' ").arg(strDevNamelist.at(0));
        }
        else
        {
            selectQuery += QString("and devName = '%1' ").arg(strDevNamelist.at(0));
        }

    }
    return selectQuery;
}


void KeyWordSearchDlg::timerEvent(QTimerEvent *event)
{
//    if(event->timerId() == myTimerId)
//    {
//        for(int i=0; i<20; i++)
//        {
//            if(item[i]->isClicked)
//            {
//                emit sendItemId(item[i]->id->text());
//                killTimer(myTimerId);
//                this->close();
//            }
//        }

//    }
}
void KeyWordSearchDlg::showEvent(QShowEvent *)
{
    myTimerId = startTimer(100);

}

void KeyWordSearchDlg::UpdateSearchResult(const QString &sqlQuery)
{
    int i = 0;  //循环变量
    QString areaTemp = "";
    QString ridgepoleTemp = "";
    QString layerTemp = "";
    QString roomTemp = "";
    QString devNameTemp = "";

    QSqlDatabase::database().transaction();
    QSqlQuery query;

    query.exec(QString("select id, area, ridgepole, layer, room, devName from"
                      "(select * from itemInfo where %1) limit %2, %3"
                      ).arg(sqlQuery).arg((pageSeq-1)*20).arg(ITEM_NUM_OF_PERPAGE));
    while(query.next())
    {
        item[i] = new SearchItem(this);
        item[i]->SetId(query.value(0).toString());

        areaTemp = query.value(1).toString();
        ridgepoleTemp = query.value(2).toString();
        layerTemp = query.value(3).toString();
        roomTemp = query.value(4).toString();
        devNameTemp = query.value(5).toString();

        QString pos = areaTemp + ridgepoleTemp + layerTemp + roomTemp;
        item[i]->SetPos(pos);
        item[i]->SetIcon(devNameTemp);

        i++;
    }
    qDebug() << "i: " << i;

    count = i;
    bottomLayout = new QGridLayout;
    for(i=0; i<count; i++)
    {
        bottomLayout->addWidget(item[i], i/5, i%5);
    }

    if(count < ITEM_NUM_OF_PERPAGE)
    {
        for(; i<ITEM_NUM_OF_PERPAGE; i++)
        {
            item[i] = new SearchItem;
            bottomLayout->addWidget(item[i], i/5, i%5);
        }
    }

    if(i != 0)
    {
        if(isEmpty == 0)
        {
            qDebug() <<"到了";
//            tmpLabel->hide();
            groupBox->setVisible(true);
            groupBox->setLayout(bottomLayout);
            mainLayout->addWidget(groupBox);
        }
        else
        {
//            tmpLabel->hide();
            mainLayout->removeWidget(groupBox);
            groupBox->close();
            groupBox = new QGroupBox(this);
            groupBox->setLayout(bottomLayout);
            mainLayout->addWidget(groupBox);
        }
        isEmpty = 1;
    }
    else
    {
        groupBox->close();
//        tmpLabel->show();

    }
    QSqlDatabase::database().commit();
}
